package com.dzsw.e2p.util;

import com.itextpdf.text.Font;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.*;

public class ExcelToPdfConverter {
    private static Font pdfFont;

    public static void convertExcelToPdf(String inputPath, String outputPath, String fontPath)
            throws Exception {
        // 初始化中文字体
        initFont(fontPath);

        // 读取Excel文件
        Workbook workbook = getWorkbook(inputPath);
        Sheet sheet = workbook.getSheetAt(0);

        // 创建PDF文档
        Document document = new Document(PageSize.A4.rotate());
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
        document.open();

        // 创建PDF表格（自动计算列宽）
        PdfPTable table = createPdfTable(sheet);
        populateTableData(sheet, table, workbook);

        document.add(table);
        document.close();
        workbook.close();
    }

    private static void initFont(String fontPath) throws Exception {
        if (fontPath != null) {
            BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            pdfFont = new Font(baseFont, 10);
        } else {
            pdfFont = FontFactory.getFont(FontFactory.HELVETICA, 10); // 备用字体
        }
    }

    private static Workbook getWorkbook(String filePath) throws IOException {
        FileInputStream inputStream = new FileInputStream(filePath);
        if (filePath.endsWith(".xlsx")) {
            return new XSSFWorkbook(inputStream);
        } else if (filePath.endsWith(".xls")) {
            return new HSSFWorkbook(inputStream);
        }
        throw new IllegalArgumentException("Unsupported file format");
    }

    private static PdfPTable createPdfTable(Sheet sheet) {
        int columns = getMaxColumnCount(sheet);
        PdfPTable table = new PdfPTable(columns);
        table.setWidthPercentage(100);
        return table;
    }

    private static int getMaxColumnCount(Sheet sheet) {
        int maxColumns = 0;
        for (Row row : sheet) {
            if (row.getLastCellNum() > maxColumns) {
                maxColumns = row.getLastCellNum();
            }
        }
        return maxColumns;
    }

    private static void populateTableData(Sheet sheet, PdfPTable table, Workbook workbook)
            throws Exception {
        // 处理合并单元格
        MergedRegionHandler mergedRegionHandler = new MergedRegionHandler(sheet);

        for (Row row : sheet) {
            for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
                Cell cell = row.getCell(cellNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

                if (mergedRegionHandler.isMergedCell(cell)) {
                    handleMergedCell(cell, table, mergedRegionHandler, workbook);
                } else {
                    addNormalCell(cell, table, workbook);
                }
            }
        }
    }

    private static void addNormalCell(Cell cell, PdfPTable table, Workbook workbook)
            throws Exception {
        PdfPCell pdfCell = createPdfCell(cell, workbook);
        table.addCell(pdfCell);
    }

    private static void handleMergedCell(Cell cell, PdfPTable table,
                                         MergedRegionHandler mergedRegionHandler, Workbook workbook) throws Exception {
        if (mergedRegionHandler.isMergeStart(cell)) {
            CellRangeAddress region = mergedRegionHandler.getMergeRegion(cell);
            PdfPCell pdfCell = createPdfCell(cell, workbook);
            pdfCell.setRowspan(region.getLastRow() - region.getFirstRow() + 1);
            pdfCell.setColspan(region.getLastColumn() - region.getFirstColumn() + 1);
            table.addCell(pdfCell);
        }
    }

    private static PdfPCell createPdfCell(Cell cell, Workbook workbook) throws Exception {
        String text = getCellValue(cell);
        PdfPCell pdfCell = new PdfPCell(new Phrase(text, pdfFont));
        applyCellStyle(cell, pdfCell, workbook);
        return pdfCell;
    }

    private static String getCellValue(Cell cell) {
        if (cell.getCellType() == CellType.FORMULA) {
            return cell.getCellFormula();
        }
        System.out.println(cell.getStringCellValue());
        DataFormatter formatter = new DataFormatter();
        return formatter.formatCellValue(cell);
    }

    private static void applyCellStyle(Cell cell, PdfPCell pdfCell, Workbook workbook) {
        CellStyle style = cell.getCellStyle();

        // 背景色
        if (style.getFillForegroundColorColor() != null) {
            XSSFColor color = (XSSFColor) style.getFillForegroundColorColor();
            pdfCell.setBackgroundColor(new BaseColor(color.getIndex()));
        }

        // 边框
        pdfCell.setBorderWidth(0.5f);
        pdfCell.setBorderColor(BaseColor.BLACK);

        // 对齐方式
        switch (style.getAlignment()) {
            case CENTER:
                pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                break;
            case RIGHT:
                pdfCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                break;
            default:
                pdfCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        }
    }

    // 合并单元格处理工具类
    private static class MergedRegionHandler {
        private final Sheet sheet;
        private final boolean[][] mergedCells;

        public MergedRegionHandler(Sheet sheet) {
            this.sheet = sheet;
            this.mergedCells = new boolean[sheet.getLastRowNum() + 1][];
            initMergedMap();
        }

        private void initMergedMap() {
            for (CellRangeAddress region : sheet.getMergedRegions()) {
                for (int row = region.getFirstRow(); row <= region.getLastRow(); row++) {
                    if (mergedCells[row] == null) {
                        mergedCells[row] = new boolean[sheet.getRow(row).getLastCellNum() + 1];
                    }
                    for (int col = region.getFirstColumn(); col <= region.getLastColumn(); col++) {
                        mergedCells[row][col] = true;
                    }
                }
            }
        }

        public boolean isMergedCell(Cell cell) {
            int row = cell.getRowIndex();
            int col = cell.getColumnIndex();
            return mergedCells.length > row &&
                    mergedCells[row] != null &&
                    mergedCells[row].length > col &&
                    mergedCells[row][col];
        }

        public boolean isMergeStart(Cell cell) {
            for (CellRangeAddress region : sheet.getMergedRegions()) {
                if (region.getFirstRow() == cell.getRowIndex() &&
                        region.getFirstColumn() == cell.getColumnIndex()) {
                    return true;
                }
            }
            return false;
        }

        public CellRangeAddress getMergeRegion(Cell cell) {
            for (CellRangeAddress region : sheet.getMergedRegions()) {
                if (region.isInRange(cell.getRowIndex(), cell.getColumnIndex())) {
                    return region;
                }
            }
            return null;
        }
    }

    public static void main(String[] args) {
        String input = "C:\\Users\\SyDevuser36\\Downloads\\Shipping Schedule.xlsx";
        String output = "D:\\output.pdf";
        try {
            // 示例调用（需提供中文字体文件路径）
            convertExcelToPdf(
                    "C:\\Users\\SyDevuser36\\Downloads\\Shipping Schedule.xlsx",
                    "D:\\output.pdf",
                    "D:\\MS-PGothic.ttf"  // 替换为实际字体路径
            );
            System.out.println("转换成功！");
        } catch (Exception e) {
            System.err.println("转换失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

